package com.fresher.controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.code.kaptcha.Producer;

@Controller
public class CaptchaCheckController {
	
	@Autowired
	private MessageSource messageSource;
	
	@Autowired
    private Producer captchaProducer;

    @RequestMapping(value = "/CaptchaCheck", method = RequestMethod.POST) 
    public void validateCaptcha(HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception{
    		
    		HttpSession session = request.getSession();
    		String c = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);  
    	    String parm = (String) request.getParameter("kaptchafield");

    	    if (c != null && parm != null) {  
                if (c.equals(parm)) {
                	request.getSession().removeAttribute("captcha");
                	request.getRequestDispatcher("/j_spring_security_check").forward (request, response);
                	System.out.println("true captcha");
                } else {  

                	String message = messageSource.getMessage("label.captcha", null, locale).toString();
                	session.setAttribute("captcha", message);
                	response.sendRedirect("login");
                	System.out.println("wrong captcha");
                }  
            }
    }
}
